package com.iiapk.grid.database;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.iiapk.gridnew.domain.Article;
import com.iiapk.gridnew.domain.ColumnType;

/**
 * @author hey
 * 管理地址数据库
 */
public class ColumnTypeManager {

	private Context context;
	private static final String TABLE_NAME = ColumnType.TABLE_NAME;
	
	public ColumnTypeManager(Context context) {
		this.context = context;
	}
	
	public synchronized void close() {
		SQLiteHelper.getInstance(context).getWritableDatabase().close();
	}
	
	public synchronized SQLiteDatabase getWritableDatabase(){
		return SQLiteHelper.getInstance(context).getWritableDatabase();
	}
	
	public synchronized SQLiteDatabase getReadableDatabase(){
		return SQLiteHelper.getInstance(context).getReadableDatabase();
	}
	
	public List<ColumnType> select(){
		List<ColumnType> list = new ArrayList<ColumnType>();
		SQLiteDatabase db=this.getReadableDatabase();
	    Cursor cur=db.query(TABLE_NAME, null, null, null, null, null,"idx asc");
	    for(cur.moveToFirst();!cur.isAfterLast();cur.moveToNext()){
	    	String id = cur.getString(cur.getColumnIndex(ColumnType.COLUMN_ID));
		     String title = cur.getString(cur.getColumnIndex(ColumnType.COLUMN_TITLE));
		     String icon = cur.getString(cur.getColumnIndex(ColumnType.COLUMN_ICON));
		     int idx = cur.getInt(cur.getColumnIndex(ColumnType.COLUMN_ORDER));
		     list.add(new ColumnType(id,title,icon,idx));
		 }
	    cur.close();
	    return list; 
	}
	    
	public void delete(String id){
	    SQLiteDatabase db=this.getWritableDatabase();
	    String where=ColumnType.COLUMN_ID+"=?";
	    String[] whereValue={id};
	    db.delete(TABLE_NAME, where, whereValue);
	}
	
	public void update(List<ColumnType> list){
		SQLiteDatabase db=this.getWritableDatabase();
		String where=Article.COLUMN_ID+"=?";
		for(ColumnType columnType : list){
			String[] whereValue={columnType.id};
		    ContentValues cv=new ContentValues(); 
		    cv.put(ColumnType.COLUMN_ID, columnType.id);
		    cv.put(ColumnType.COLUMN_TITLE, columnType.title);
		    cv.put(ColumnType.COLUMN_ICON, columnType.icon);
		    cv.put(ColumnType.COLUMN_ORDER, columnType.idx);
		    db.update(TABLE_NAME, cv, where, whereValue); 
		}
	}	
	
}
